/*
 * @Author: CPS
 * @Date: 2020-07-25 18:01:11
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-11 00:20:31
 * @Projectname Electron-fileWatcher
 * @Filename index.js
 */


'use strict'
import icon from './icon/icon.js'
import template from './template/container.pug'
import './template/component.stylus'

function prefix(name) {
  return 'cpsDialog__' + name
}

class createDialog {
  constructor() {
    // 判断body下是否已存在
    this.el = document.getElementById(prefix('component'))

    console.log('开始创建cpsDialog对象')
    if (!this.el) {
      this.el = document.createElement('section')
      this.el.id = this.el.className = prefix('component')
    }

    this.data = {
      mode: '',
      content: '',
      icon: icon
    }

    this.show([{
      text: '密码:',
    }, {
      text: '单击输入',
      type: 'password',
      name: 'password'
    }], (res, data) => {
      if (res) console.log(data)
    })

    // 挂载到body
    document.body.style.position = 'relative'
    document.body.appendChild(this.el)
  }

  /**
   * 弹出一个窗口,接收一个处理函数
   *
   * @param      {<type>}              data      {text:'元素的内容',input:'输入框的默认内容',type:'输入框的类型'}
   * @param      {(Function|boolean)}  callback  回调函数, 回调参数1 用户的选择 回调参数2 输入的数据集合
   * 数据格式:
     1 单行数据 {text:'元素的内容',input:'输入框的默认内容',type:'输入框的类型',name:'输入框的name字段'}
     2 单行多元素 [{},{}]
     3 多行多元素 [[{},{}],[{},{}],[{},{}]]
  */

  show(data = null, callback = false) {
    if (!data) return

    // 判断输入类型
    if (!Array.isArray(data)) {
      //console.log('单行单列数据')
      this.data.mode = 'row'
    } else if (!Array.isArray(data[0])) {
      // console.log('单行多列数据')
      this.data.mode = 'cols'
    } else {
      //console.log('多行多列数据')
      this.data.mode = 'rows'
    }

    this.data.content = data
    this.el.innerHTML = template(this.data)

    // 传送处理函数到监听器
    this.el.addEventListener('click', (e) => {
      let tar = e.target.className
      switch (tar) {
        case prefix('btn-ture'):
          // console.log('用户点击了确认')
          let res = {}
          let resList = this.el.getElementsByClassName(prefix('item-input'))
          if (resList.length >= 1) {
            for (let eachElement of resList) {
              res[eachElement.name] = eachElement.value
            }
          }

          if (callback) callback(1, res)
          break;
        case prefix('btn-false'):
          // console.log('用户点击了取消')
          if (callback) callback(0, '用户点击了取消')
          this.close()
          break;
        default:
          // statements_def
          console.log('用户点击了:' + tar)
          break;
      }
    }, true)

    if (this.el && this.el.style.display == 'none') {
      this.el.style.display = 'inline'
    }
  }

  close() {
    if (this.el && this.el.style.display != 'none') {
      this.el.style.display = 'none'
    }
  }
}



export default createDialog